#!/bin/bash

# MySQL 8 数据库和用户创建脚本
# 用法: ./create_mysql_db_user.sh <数据库名> <用户名>

if [ $# -ne 2 ]; then
    echo "用法: $0 <数据库名> <用户名>"
    echo "示例: $0 myapp appuser"
    exit 1
fi

DATABASE="$1"
USERNAME="$2"
PASSWORD=$(openssl rand -base64 12 | tr -d "=+/" | cut -c1-16)

echo "-- MySQL 8 数据库和用户创建脚本"
echo "-- 生成时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo "-- 数据库: $DATABASE"
echo "-- 用户: $USERNAME"
echo "-- 密码: $PASSWORD"
echo ""

echo "-- 1. 创建数据库（不区分大小写）"
echo "CREATE DATABASE IF NOT EXISTS \`$DATABASE\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
echo ""

echo "-- 2. 创建用户并设置密码（使用传统认证方式）"
echo "CREATE USER IF NOT EXISTS '$USERNAME'@'%' IDENTIFIED WITH mysql_native_password BY '$PASSWORD';"
echo ""

echo "-- 3. 授予用户对数据库的所有权限"
echo "GRANT ALL PRIVILEGES ON \`$DATABASE\`.* TO '$USERNAME'@'%';"
echo ""

echo "-- 4. 刷新权限"
echo "FLUSH PRIVILEGES;"
echo ""

echo "-- 5. 显示创建结果"
echo "SHOW DATABASES LIKE '$DATABASE';"
echo "SELECT User, Host FROM mysql.user WHERE User = '$USERNAME';"
